package com.zlz.parent.basic.springboot.starter.trace;

import com.zlz.parent.basic.springboot.starter.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class TraceFilter implements WebFilter, Ordered {

    private final IdWorker idWorker;

    public TraceFilter(IdWorker idWorker) {
        this.idWorker = idWorker;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        log.debug("TraceFilter: Start Init TraceId");
        TraceContext.init(LoginContext.builder().traceId(idWorker.nextId() + "").build());
        MDC.put("traceId", TraceContext.getUserInfo().getTraceId());
        log.debug("TraceFilter: Init TraceId Success-[{}]", TraceContext.getUserInfo().getTraceId());
        exchange.getResponse().getHeaders().set("X-Trace-Id", TraceContext.getUserInfo().getTraceId());
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 100;
    }
}

